/**
 * 每天00：00检查临近过期的项目
 * 并发短消息通知 项目管理员 项目执行人员
 */
const _ = require('lodash');
const moment = require('moment');
module.exports = {
  schedule: {
    immediate: false,
    cron: '0 0 0 * * *', // 每天00：00检查
    type: 'worker', // 指定一个 worker 执行
    env: ['prod'],// 在prod环境才执行
  },
  async task(ctx) {
    let app = ctx.app;
    let {Project, User, Message, UserMessage} = app.model;
    let now = moment().startOf('day'),
        expireTime = moment().add(11, 'day').endOf('day').toDate();
    let projects = await Project.findAll({
      where: {
        end_at: {[app.Sequelize.Op.between]: [new Date(), expireTime]},
      },
      include: [{model: User, as: 'user', attributes: ['id']}],
    });

    // console.log('project length 1', projects.length);
    if (_.isEmpty(projects))
      return;
    projects = projects.filter(project => {
      let diff = Math.abs(now.diff(moment(project.end_at), 'd'));
      console.log(project.id, diff);
      //距离现在 1天，3天，5天，10天
      return (diff === 1 || diff === 3 || diff === 5 || diff === 10);
    });
    // console.log('project length 2', projects.length);

    if (_.isEmpty(projects))
      return;

    let user_id = [];
    //给用户发项目提醒短消息
    _.each(projects, project => {
      let id = project.user.map(user => user.id);
      user_id.push(...id);
      let content = messageContent(project.name, project.end_at);
      Message.create({title: '临近项目的结束时间提醒', content, from_id: 1}).
          then(message => {
            let userMessages = project.user.map(
                user => ({message_id: message.id, user_id: user.id}));
            UserMessage.bulkCreate(userMessages);
          });
    });
    //过滤重复的用户ID
    user_id = _.compact(_.uniq(user_id));
    //设置用户的新消息通知
    User.update({message: 1}, {where: {id: {[app.Sequelize.Op.in]: user_id}}});
  },
};

function messageContent(projectName, expiredTime) {
  expiredTime = moment(expiredTime).format('YYYY-MM-DD');
  return `${projectName} 将于 ${expiredTime} 到期，如有需要，请尽快在项目管理下修改运营结束时间。`;
}